package cn.itcast.bos.web.action.base;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.base.SubArea;
import cn.itcast.bos.service.base.SubAreaService;
import cn.itcast.bos.web.action.common.BaseAction;
import com.opensymphony.xwork2.ActionContext;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
@Scope("prototype")
@Namespace("/")
@ParentPackage("json-default")
public class SubAreaAction extends BaseAction<SubArea> {

    @Autowired
    private SubAreaService subAreaService;

    @Action(value = "subarea_save",results = {@Result(name = "success",location = "./pages/base/sub_area.html",type = "redirect"),
            @Result(name = "input",location = "/index.html",type = "redirect")})
    public String subAreaSave(){
        subAreaService.save(model);
        return SUCCESS;
    }

    @Action(value = "subArea_pageQuery",results = {@Result(name = "success",type = "json"),
            @Result(name = "input",location = "/index.html",type = "redirect")})
    public String pageQuery(){
        Pageable pageable = new PageRequest(page-1,rows);

        Specification<SubArea> specification = new Specification<SubArea>() {
            @Override
            public Predicate toPredicate(Root<SubArea> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                //判断area是否为空,优化代码逻辑
                /**
                 * 添加区域条件查询
                 */
                if (model.getArea() != null) {
                    Join<SubArea, Area> subAreaJoin = root.join("area", JoinType.INNER);
                    if (StringUtils.isNotBlank(model.getArea().getProvince())) {
                        Predicate p1 = cb.like(subAreaJoin.get("province").as(String.class), "%" + model.getArea().getProvince() + "%");
                        list.add(p1);
                    }
                    if (StringUtils.isNotBlank(model.getArea().getCity())) {
                        Predicate p2 = cb.like(subAreaJoin.get("city").as(String.class), "%"+model.getArea().getCity()+"%");
                        list.add(p2);
                    }
                    if (StringUtils.isNotBlank(model.getArea().getDistrict())) {
                        Predicate p3 = cb.like(subAreaJoin.get("district").as(String.class), "%" + model.getArea().getDistrict() + "%");
                        list.add(p3);
                    }
                }
                /**
                 * 添加条件fixedArea
                 */
                Join<SubArea, FixedArea> fixedAreaJoin = root.join("fixedArea", JoinType.INNER);
                if (model.getFixedArea() != null && StringUtils.isNotBlank(model.getFixedArea().getId())) {
                    Predicate p4 = cb.equal(fixedAreaJoin.get("fixedArea").as(String.class), model.getFixedArea().getId());
                    list.add(p4);
                }
                /**
                 * 添加条件关键字查询
                 */
                if (StringUtils.isNotBlank(model.getKeyWords())) {
                    Predicate p5 = cb.like(root.<String>get("keyWords").as(String.class), "%" + model.getKeyWords() + "%");
                    list.add(p5);
                }
                return cb.and(list.toArray(new Predicate[0]));
            }
        };
        Page<SubArea> pageData = subAreaService.findPageData(specification,pageable);
        pushPageDataToValueStack(pageData);
        return SUCCESS;
    }

    //添加一键上传的业务代码实现
    //接受文件上传的数据
    private File file;
    private String fileFileName;

    public void setFile(File file) {
        this.file = file;
    }

    public void setFileFileName(String fileFileName) {
        this.fileFileName = fileFileName;
    }

    @Action(value = "subrea_batchImport",results = {@Result(name = "success",location = "./pages/base/sub_area.html",type = "redirect"),
            @Result(name = "input",location = "/index.html",type = "redirect")})
    public String subAreaBatchImport(){
            String msg = "";
        try {
            //接受文件上传后的回显回显信息
            List<SubArea> subAreas = new ArrayList<>();
            //读取上传文件
            Workbook workbook = null;
            //判断文件类型,根据文件类型选择不同的解析方式,判断是否为空如果为空,请重新选择
            if (fileFileName ==null) {
                //返回不执行下边的语句
                return  msg ="请选择一个表格数据文件";
            }else{
                if (fileFileName.endsWith(".xls")) {
                    //接受.xls的文件
                    workbook = new HSSFWorkbook(new FileInputStream(file));
                }else {
                    workbook = new XSSFWorkbook(file);

                }
            }
           //获取第一个工作簿
            Sheet sheetAt = workbook.getSheetAt(0);

            //遍历每一行
            for (Row row : sheetAt) {
                //第一行为表头,跳过
                if (row.getRowNum() ==0) {
                    continue;
                }
                //如果表格为null或者为""空串也跳过
                if (StringUtils.isBlank(row.getCell(0).getStringCellValue()) || row.getCell(0) == null) {
                    continue;
                }

                //读取下边每一行
                SubArea subArea  = new SubArea();
                FixedArea fixedArea = new FixedArea();
                Area area = new Area();
                subArea.setId(row.getCell(0).getStringCellValue());
                fixedArea.setId(row.getCell(1).getStringCellValue());
                subArea.setFixedArea(fixedArea);
                area.setId(row.getCell(2).getStringCellValue());
                subArea.setArea(area);
                subArea.setKeyWords(row.getCell(3).getStringCellValue());
                subArea.setStartNum(row.getCell(4).getStringCellValue());
                subArea.setEndNum(row.getCell(5).getStringCellValue());
                char[] chars = row.getCell(6).getStringCellValue().toCharArray();
                subArea.setSingle(chars[0]);
                subAreas.add(subArea);
            }
            System.out.println(subAreas);
            subAreaService.saveBath(subAreas);
            msg = "上传成功...";
        } catch (Exception e) {
            e.printStackTrace();
            msg = "上传失败...";
        }
        try {
            ServletActionContext.getResponse().getWriter().write(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return SUCCESS;
    }

    @Action(value = "subarea_export",results = {@Result(name = "success",location = "./pages/base/sub_area.html",type = "redirect"),
            @Result(name = "input",location = "/index.html",type = "redirect")})
    public String subAreaExport(){
        //查找所有的分区选项
        List<SubArea> subAreas = subAreaService.findAll();
        //创建写入excel的数据表格
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook();
        //一般一个数据表写入的值是固定的也不是太多
        int totalNum = (int) Math.ceil(subAreas.size() * 1.0 / 5000);
        for (int i = 0; i < totalNum; i++) {
            //创建工作簿
            XSSFSheet sheet = xssfWorkbook.createSheet("分区数据表" + (i + 1));
            //创建行,一般第一行为表头
            XSSFRow firstRow = sheet.createRow(0);
            firstRow.createCell(0).setCellValue("分拣编号");
            firstRow.createCell(1).setCellValue("省");
            firstRow.createCell(2).setCellValue("市");
            firstRow.createCell(3).setCellValue("区");
            firstRow.createCell(4).setCellValue("关键字");
            firstRow.createCell(5).setCellValue("起始号");
            firstRow.createCell(6).setCellValue("终止号");
            firstRow.createCell(7).setCellValue("单双号");
            firstRow.createCell(8).setCellValue("辅助关键字");

            //最后一页问题,当
            int start = i*5000;
            int end = (i+1)*5000;
            if (end >= subAreas.size()) {
                end = subAreas.size();
            }
            for (int j = start; j < end; j++) {
                //获取遍历到最后一行的行号
                XSSFRow row = sheet.createRow(sheet.getLastRowNum() + 1);
                SubArea subArea = subAreas.get(j);
                row.createCell(0).setCellValue(subArea.getId());
                row.createCell(1).setCellValue(subArea.getArea().getProvince());
                row.createCell(2).setCellValue(subArea.getArea().getCity());
                row.createCell(3).setCellValue(subArea.getArea().getDistrict());
                row.createCell(4).setCellValue(subArea.getKeyWords());
                row.createCell(5).setCellValue(subArea.getStartNum());
                row.createCell(6).setCellValue(subArea.getEndNum());
                row.createCell(7).setCellValue(subArea.getSingle());
                row.createCell(8).setCellValue(subArea.getAssistKeyWords());

            }
                //提供下载获取输出流
            HttpServletResponse response = ServletActionContext.getResponse();
            //文件下载的两个头
            //设置下载文件的名字
            String fileName = "fqsjb.xlsx";
            String mimeType = ServletActionContext.getServletContext().getMimeType(fileName);
            //设置文件类型
            response.setContentType(mimeType);
            //设置头
            response.setHeader("content-disposition","attachment;filename="+fileName);
            //写入数据
            try {
                xssfWorkbook.write(response.getOutputStream());

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return SUCCESS;
    }

}
